package com.zking.forward.shopping;

import com.zking.dao.ProductDao;
import com.zking.dao.ShopCarDao;
import com.zking.entity.Product;
import com.zking.entity.ShopCar;
import com.zking.entity.User;
import com.zking.util.RedirectMsg;
import com.zking.util.Tools;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/shopcarList")
public class ShopcarList extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //处理请求的编码，解决中文乱码
        request.setCharacterEncoding("utf-8");
        //处理响应的编码 ，解决中文乱码
        response.setContentType("text/html;charset=utf-8");

        System.out.println("ShopcarList===进来");

        //根据当前登录的用户的得到他对应购物车
        User user = (User)request.getSession().getAttribute("user");
        // 对没登陆情况的处理
//        if(user==null){
//            request.setAttribute("msg", RedirectMsg.notLogin);
//            request.setAttribute("pageName", RedirectMsg.loginPageName);
//            request.setAttribute("url", RedirectMsg.loginUrl);
//            request.getRequestDispatcher("redirect.jsp").forward(request, response);
//            return;
//        }
        String eu_user_id = user.getEu_user_id();
        //根据用户的编号到购物车表中得到对应的数据--pid商品编号  count数量
        List<ShopCar> shopList = ShopCarDao.selectShopCarById(eu_user_id);
        List<Product> list = new ArrayList<Product>();
        List<String> images = new ArrayList<>();
        for (ShopCar shopCar : shopList) {
            Integer ep_id = shopCar.getEp_id();
            Product product = ProductDao.selectProductById(ep_id);
            if(product==null){
                continue;
            }
            product.setCount(shopCar.getCount());
            images.add(Tools.bytesToString(product.getEp_image_bytes()));
            list.add(product);
        }

        request.setAttribute("list", list);
        request.setAttribute("images", images);
        request.getRequestDispatcher("shopping.jsp").forward(request, response);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
